import React, {Component} from 'react';
import {configure} from 'mobx';
import {Platform, BackHandler, ToastAndroid, YellowBox} from 'react-native';
import SplashScreen from 'react-native-splash-screen';
import {createSwitchNavigator} from 'react-navigation';
import Load from './routers/navigation/Load';
import Auth from './routers/navigation/Auth';
import Gesture from './routers/navigation/Gesture';
import Main from './routers/navigation/Main';
configure({enforceActions: true});

YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated in plain JavaScript React classes.',
    'Module RCTImageLoader requires main queue setup since it overrides `init` '])

const Root = createSwitchNavigator(
    {
        Load: Load,//加载验证逻辑
        Auth: Auth,//登陆认证过程
        Gesture: Gesture,//手势密码认证
        Main: Main,//系统业务主页
    },
    {
        initialRouteName: 'Load'
    }
);

export default class App extends Component {
    componentDidMount() {
        // do anything while splash screen keeps, use await to wait for an async task.
        SplashScreen.hide();//关闭启动屏幕

        if (Platform.OS === 'android') {
            BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
        }
    }

    componentWillUnmount() {
        if (Platform.OS === 'android') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
        }
    }

    onBackAndroid = () => {
        if (!this.isFirstScreen) {
            return false;
        } else if (this.isFirstScreen && this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
            //最近2秒内按过back键，可以退出应用。
            return false;
        } else {
            this.lastBackPressed = Date.now();
            ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
            return true;
        }
    };

    render() {
        return <Root onNavigationStateChange={(prevState, currentState) => {
                const currentScreen = getActiveRouteName(currentState);
                const prevScreen = getActiveRouteName(prevState);
                this.isFirstScreen = currentScreen === 'Home';
            }}
        />;
    }
}

function getActiveRouteName(navigationState) {
    if (!navigationState) {
        return null;
    }
    const route = navigationState.routes[navigationState.index];
    if (route.routes) {
        return getActiveRouteName(route);
    }
    return route.routeName;
}